/*
 * @description: 
 * @Author: chuyinlong
 * @Date: 2021-07-19 09:13:57
 * @LastEditors: chuyinlong
 * @LastEditTime: 2021-08-06 11:10:58
 */
// 店铺设置模块                                                                                               
import { Module } from "vuex"
import { isPrimeNum } from "@/utils";
// import { getEvaluateSetting, getOrderSetting } from "@/api/modules/order";
import {
  getSetting,
  getGuide,
  getGuideVisible,
  getRecyclingSetting,
} from "@/api/modules/global";
import { getAggregate } from "@/api/modules/userCenter";
import { getIntegralRule } from "@/api/modules/integral";
import {
  // getControl,
  // getTemplate,
  getAllRegionList,
  getDecorationAll,
} from "@/api/modules/decoration";
// import { wxp } from "@/base";
import storage from "@/utils/storage";
// import isEqual from "lodash/isEqual";
import { isEqual } from 'lodash';
// import { Prop } from "vue/types/options";

type ITabName = "home" | "mall" | "shopCar" | "spike" | "group" | "me" | "";

export interface IOrderSetting {
  ceiling: number;
  customFrom: string;
  id: number;
  kdAppId: string;
  kdAppKey: string;
  orderNotify: true;
  paymentModel: string;
  ratio: number;
  shopId: string;
  supportAllowedDay: number;
  supportAuditDay: number;
  type: string;
}

export interface IShopSetting {
  /** 是否开启评价 */
  hasOpenEvaluate: boolean,
  /** 返利设置 */
  rebateSet: { [key: string]: string | number },
  /** 是否开启会员功能 */
  openMember: boolean,
  /** 当前店铺信息 */
  curShopInfoDto: { [key: string]: string | number },
}

type TypeNumber = 1 | 0


type objectdata = {
  [key: string]: string | number | boolean | objectdata
}


const module: Module<Record<string, any>, Record<string, any>> = {
  namespaced: true,
  state: {
    /** 店铺设置 */
    shopSetting: {
      hasOpenEvaluate: false,
      rebateSet: {},
      openMember: false,
      curShopInfoDto: {},
    } as IShopSetting,

    /** 是否准备完毕 */
    isReady: false,

    /** 引导页是否显示 */
    guideVisible: false,

    /** 当前自定义页面 */
    linkPageId: "" as string | number,

    /** 首页tab显示隐藏 主要为了解决cover-view 层级最高的问题 */
    tabVisible: true,

    /** 当前选中tab */
    currentTab: "",

    /** 搜索页面定义搜索词 */
    searchName: "",

    /** 当前自定义页面id */
    currentPageId: "" as string | number,

    /** homeTab的信息obj（跳转页面前判断type==5为自定义页面，需要将store中currentPageId置为homeTab的id,然后跳转;非type==5,跳转linkUrl的地址） */
    homeTab: {} as objectdata,

    /** 使用中的模板 */
    templateId: "" as string | number,

    /** 重新请求自定义装修数据的id */
    newCurrentPageId: "" as string | number,

    /** 页面列表 */
    pageList: [] as objectdata[],

    /** 是否转发进入 */
    iftransFrom: false,

    /** 是否进入过自定义页面 */
    hasInCustom: false,

    /** 自定义页面名称 */
    customName: "",

    /** 获取需要进入的自定义页面的新id */
    customPageId: "" as string | number,

    /** 首页标题 */
    indexTitle: "首页",

    /** 重新设置底部选中对象 */
    isReSet: false,

    /** 购物车规格弹窗息屏问题 */
    formShopCar: false,

    /** 订单信息 */
    order: {} as IOrderSetting,

    /** 顶部导航栏高度 */
    navigationBarHeight: 0,

    /** tabBar数据 */
    tabBar: {
      mode: "default",
      color: "#7A7E83",
      selectedColor: "#F64E3F",
      background: "#ffffff",
      list: [],
      selectColor: "#F64E3F",
      defaultColor: "#7A7E83",
    },

    /** 积分规则 */
    integral: {
      load: false,
    },

    /** 自定义页面控件数据 */
    components: [] as any[],

    /** 装修数据-拼团分类页 */
    spellPage: {},

    /** 装修数据-商超分类页 */
    businessSuper: {},

    /** 个人中心配置数据 */
    userCenter: {},

    /** 判断是不是从底部导航跳转的 */
    notSwitchTab: 0,

    /** 跳转自定义和首页的历史纪录*/
    historyPage: [],

    /** 引导页数据 */
    guideList: [],

    newCurrentPage: null as any,

    /** 专区id */
    saleMode: "" as string | number,

    /** 分类页所在专区 */
    modeType: 1 as TypeNumber, // 拼团专区0 商超专区1

    /** 自定义分类页标题 */
    customPageName: "",

    centerTabbarItem: {},

    /** 当前店铺回收、基金相关配置 */
    recyclingsetting: {} as any,


  },
  getters: {

  },
  mutations: {

    /** 
     * @description 设置是否开启转发进入状态
     * @param res true开启 false关闭
     */
    setIftransFrom(state: any, res: boolean) {
      state.iftransFrom = res;
    },

    /** 
     * @description 设置当前店铺回收、基金相关配置 
     * @param res 回收、基金相关配置
     */
    setRecyclingsetting(state: any, res: any): void {
      state.recyclingsetting = res;
    },

    /** 
     * @description 设置是否开启引导页 
     * @param res true开启 false关闭
     */
    setGuideVisible(state: any, res: boolean): void {
      state.guideVisible = res;
    },

    /** 
     * @description 设置自定义分类页标题 
     * @param res 标题名
     */
    setCustomPageName(state: any, res: string): void {
      state.customPageName = res;
    },

    /** 
     * @description 设置自定义页面名称
     * @param res 名称
     */
    setcustomName(state: any, res: string) {
      state.customName = res
    },

    /**
     * @description 设置当前tab
     * @param tab "" | "home" | "mall" | "shopCar" | "spike" | "group" | "me"
     */
    setCurrentTab(state: any, tab: ITabName) {
      state.currentTab = tab;
    },

    /** 
     * @description 设置准备完毕 
     */
    setIsReady(state: any) {
      state.isReady = true;
    },

    /**
     * @description 设置当前自定义页面id
     * @param id
     */
    setCurrentPageId(state: any, id: string | number = "") {
      console.log("currentPageId",id)
      state.currentPageId = id;
    },

    /**
     * @description 设置新的id
     * @param id 
     */
    setNewCurrentPageId(state: any, id: string | number = "") {
      state.newCurrentPageId = id;
    },

    /**
     * @description 设置tab显示状态
     * @param status true显示 false关闭
     */
    setTabVisible(state: any, status: boolean) {
      state.tabVisible = status;
    },

    /** 
     * @description 设置引导页配置
     * @param res 引导页列表
     */
    setGuideList(state: any, res: any[]) {
      state.guideList = res
    },

    /** 
     * @description 设置订单设置 
     * @param res 订单设置数据
     */
    setOrder(state: any, res: IOrderSetting) {
      state.order = res
    },

    /** 
     * @description 设置店铺基本信息 
     * @param data 店铺基本信息数据
     */
    setShopSetting(state: any, data: IShopSetting) {
      state.shopSetting = data
    },

    /** 
     * @description 设置首页标题 
     * @param name 标题名
     */
    setIndexTitle(state: any, name: string) {
      state.indexTitle = name
    },

    /** 
     * @description 设置个人中心数据 
     * @param data 用户中心数据
     */
    setUserCenter(state: any, data: any) {
      state.userCenter = data
    },

    /** 
     * @description 设置页面装修数据
     * @param nid 页面ID
     */
    setComponents(state: any, components: any) {
      state.components = components
    },

    /**
     * @description 设置页面装修模板ID
     * @param data 页面装修模板ID
     */
    setTemplateId(state: any, data: string | number) {
      state.templateId = data
    },

    /**
     * @description 设置页面数据
     * @param data 页面数据
     */
    setPageList(state: any, data: any) {
      state.pageList = data
    },

    /**
     * @description 设置tabBar数据
     * @param data 
     */
    setTabBar(state: any, data: {
      mode: string,
      color: string,
      selectedColor: string,
      background: string,
      list: any[],
      selectColor: string,
      defaultColor: string,
    }) {
      state.tabBar = data
    },

    /**
     * @description 设置homeTab的信息obj
     * @param data 
     */
    setHomeTab(state: any, data: Record<string, unknown>) {
      state.homeTab = data
    },

    /**
     * @description 设置
     * @param data 
     */
    setCenterTabbarItem(state: any, data: Record<string, unknown>) {
      state.centerTabbarItem = data
    },

    /**
     * @description 设置积分开关
     * @param data 开关状态true|false
     */
    setIntegral(state: any, data: boolean) {
      state.integral.load = data
    },

    /**
     * @description 设置新进入的自定义页面的ID
     * @param data 自定义页面ID
     */
    setCustomPageId(state: any, data: string | number) {
      state.customPageId = data
    },

    /**
     * @description 设置是否进入过自定义页面
     * @param data true|false
     */
    setHasInCustom(state: any, data: boolean) {
      state.hasInCustom = data
    },

    /**
     * @description 重新设置底部选中对象
     * @param data 
     */
    setIsReSet(state: any, data: boolean) {
      state.isReSet = data
    },

    /**
     * @description 设置导航栏高度
     * @param data 
     */
    setNavigationBarHeight(state: any, data: number) {
      state.navigationBarHeight = data
    },

    setSellPage(state: any, data: { spellPage: any, businessSuper: any }) {
      state.spellPage = data.spellPage
      state.businessSuper = data.businessSuper
    },

    setShowTabBar(state: any, itemLink: { type: number, url: string, append: string, id: number, sortIndex: number }) {
      const tabBar = state.tabBar;
      const arr = tabBar.list.filter(
        (item: { type: number; linkUrl: string; name: string; id: number; }) =>
          !!item &&
          item.type === itemLink.type &&
          item.linkUrl === itemLink.url &&
          item.name === itemLink.append &&
          item.id === itemLink.id,
      );

      if (!arr.length) {
        state.notSwitchTab = 1;
      } else {
        state.notSwitchTab = 0;
      }
      if (state.currentPageId > 6 && itemLink.sortIndex !== 0) {
        state.notSwitchTab = 1;
      }
    },

    setSwitchTab(state: any, data: number) {
      state.notSwitchTab = data;
    },

    setHistoryPage(state: any, data: any) {
      state.historyPage.push(data)
    },

    setNewCurrentPage(state: any, data: any) {
      state.newCurrentPage = data
    },

    setFormShopCar(state:any,data:boolean){
      state.formShopCar = data
    },

    setSaleMode(state:any,data:string|number){
      state.saleMode = data
    }
  },
  actions: {

    /** 
     * @description 当前店铺回收、基金相关配置 
     */
    async getRecyclingSetting(context) {
      const res = await getRecyclingSetting();
      context.commit('setRecyclingsetting', res);
    },

    /**
     * @description  获取是否开启引导页 
     */
    async getGuideVisible(context) {
      const res = await getGuideVisible();
      context.commit('setGuideVisible', !!res);
    },

    /** 
     * @description 判断当前分类页是拼团OR商超
     * @param id 当前分类页ID
     */
    async getPageType(context, id: string | number) {
      let selectItem = {} as objectdata[];
      const res = await getAllRegionList({})
      selectItem = res.filter((item: { id: string | number; }) => Number(item.id) === Number(id));
      if (selectItem.length > 0) {
        context.commit('setCustomPageName', selectItem[0].modeName)
      }
    },

    /**
     * 获取引导页设置
     */
    async getGuideList(context) {
      const res = await getGuide()
      const list = res.filter((item: { url: string; }) => !!item.url)
      context.commit('setGuideList', list)
    },

    /**
     * @description 获取店铺设置
     * @returns miniMsgVoList
     */
    async getSetting(context) {
      const {
        openEvaluate,
        setting,
        miniMsgVoList,
        rebateSet,
        openMember,
        mergePoint,
        curShopInfoDto,
      } = await getSetting();
      const data = {
        hasOpenEvaluate: !!openEvaluate,
        rebateSet: rebateSet,
        openMember: openMember,
        curShopInfoDto: curShopInfoDto,
        mergePoint: mergePoint === "0",
      }
      context.commit('setShopSetting', data)
      context.commit('setOrder', setting)
      context.commit('setIndexTitle', curShopInfoDto.shopName)
      return miniMsgVoList;
    },


    /**
     * @description 获取个人中心数据并缓存
     * @param context 当前store自带类
     */
    async getAllUserCenterData(context) {
      const storageData = storage.get("getAllUserCenterData");
      const res = await getAggregate();
      if (res && !isEqual(res, storageData)) {
        storage.set("getAllUserCenterData", res, 3 * 24 * 60 * 60 * 1000);
        context.commit('setUserCenter', res)
      } else {
        context.commit('setUserCenter', storageData)
      }
    },

    setNewJump(context, { nid, name }) {
      const showPage = context.state.pageList.filter((item: { id: string | number; }) => {
        return Number(item.id) === Number(nid);
      });
      const components = [] as any;
      const assemblyVos = showPage[0].assemblyVos;
      if (assemblyVos.length > 0) {
        assemblyVos.forEach((item: { properties: string; }) => {
          const properties = JSON.parse(item.properties);
          components.push(properties);
        });
      }
      context.commit('setComponents', components)
      context.commit('setIndexTitle', name)
    },

    /** 
     * @description 获取聚合装修接口数据
     * @param nid 
     */
    async getDecorationAllList(context, nid = "") {
      const res = await getDecorationAll();
      if (res && !isEqual(res, storage.get("getDecorationAllListData"))) {
        storage.set("getDecorationAllListData", res, 3 * 24 * 60 * 60 * 1000);
      }
      const storageData = storage.get("getDecorationAllListData");
      if (!storageData) {
        uni.showToast({
          title: "接口无数据",
          icon: "none",
        });
        return;
      }
      const data = storageData.data || storageData;
      const plugins = data.plugins;
      const pages = data.pages;
      const id = data.id;
      await context.dispatch('parseControlList', plugins)
      await context.dispatch('parseAssembleList', { pages, nid })
      context.commit('setTemplateId', id)
      const newPages = data.pages.filter((item: { isDef: string; }) => {
        return item.isDef === "1";
      });
      if (!newPages.length) {
        uni.showToast({
          title: "无首页数据",
          icon: "none",
        });
      } else {
        context.commit('setNewCurrentPageId', newPages[0].id)
      }
      context.commit('setPageList', pages)
    },

    /**
     * @description 解析配置控件数据
     * @param plugins 配置控件数据
     */
    async parseControlList(context, plugins: any[]) {
      let formdata = null;
      const navbar = plugins.filter((item: { pluginNameEn: string }) => {
        return item.pluginNameEn === "navBar";
      });
      formdata = JSON.parse(navbar[0].pluginProperties)[0].formData || null;

      const navBarform = formdata ? formdata : null;
      const handleIcon = await context.dispatch("handleIcon", formdata.menuList)
      const navBarPlugin = navBarform ? handleIcon : null;
      const tabBar = {
        ...context.state.tabBar,
        selectColor: formdata ? formdata.selectColor : "#F64E3F",
        defaultColor: formdata ? formdata.defaultColor : "#7A7E83"
      }
      context.commit('setTabBar', tabBar)
      await context.dispatch("getPlugins", navBarPlugin)
      await context.dispatch("settingBigPic", navBarform)
    },


    /** 解析自定义页面组件数据 */
    parseAssembleList(context, { pages, nid }) {
      const components: any[] = [];
      let assembleList: any[] = [];
      if (!nid) {
        assembleList = pages.filter((item: { isDef: string; }) => item.isDef === "1");
      } else {
        assembleList = pages.filter((item: { id: any; }) => Number(item.id) === Number(nid));
        context.commit('sethasInCustom', false)
      }
      if (!assembleList.length) {
        uni.showToast({
          title: "未获取到首页数据！",
          icon: "none",
        });
        return;
      }
      const assemblyVos = assembleList[0].assemblyVos;
      if (assemblyVos.length > 0) {
        assemblyVos.forEach((item: { properties: string; }) => {
          const properties = JSON.parse(item.properties);
          components.push(properties);
        });
      }
      context.commit('setComponents', components)
      // 处理分类页页面数据
      const spell = pages.find((i: { type: string; }) => i.type === "1");
      const businessSuper = pages.find((i: { type: string; }) => i.type === "2");
      const spellPage = spell
        ? spell.assemblyVos[0]
          ? JSON.parse(spell.assemblyVos[0].properties)
          : {}
        : {};
      const businessSuperdata = businessSuper
        ? businessSuper.assemblyVos[0]
          ? JSON.parse(businessSuper.assemblyVos[0].properties)
          : {}
        : {};
      context.commit('setSellPage', { spellPage, businessSuperdata })
    },



    /**
     * @description 处理系统图标
     * @param menuList 
     * @returns 菜单列表数据
     */
    handleIcon(_context, menuList: any[]) {
      const icons = [
        {
          def: "https://oss-tencent.bgniao.cn/api/home_page.png",
          act: "https://oss-tencent.bgniao.cn/api/home_page1.png",
        },
        {
          def: "https://oss-tencent.bgniao.cn/api/shopping_mall1.png",
          act: "https://oss-tencent.bgniao.cn/api/shopping_mall.png",
        },
        {
          def: "https://oss-tencent.bgniao.cn/api/shopping_cart1.png",
          act: "https://oss-tencent.bgniao.cn/api/shopping_cart.png",
        },
        {
          def: "https://oss-tencent.bgniao.cn/api/my1.png",
          act: "https://oss-tencent.bgniao.cn/api/my.png",
        },
        {
          def:
            "https://medusa-small-file-1253272780.cos.ap-shanghai.myqcloud.com/gruul/20210112/b2ef1106af8b4a6c9b22ee0afac6195c.png",
          act:
            "https://medusa-small-file-1253272780.cos.ap-shanghai.myqcloud.com/gruul/20210112/613afce069ca4cfdb980cd446e0195f1.png",
        },
      ];
      if (menuList.length < 5) {
        menuList.forEach((menu, index) => {
          if (menu.iconType === 1) {
            menu.iconPath = icons[index].def;
            menu.selectedIconPath = icons[index].act;
          }
        });
      } else {
        if (menuList[0].iconType === 1) {
          menuList[0].iconPath = icons[0].def;
          menuList[0].selectedIconPath = icons[0].act;
        }
        if (menuList[1].iconType === 1) {
          menuList[1].iconPath = icons[1].def;
          menuList[1].selectedIconPath = icons[1].act;
        }
        if (menuList[2].iconType === 1) {
          menuList[2].iconPath = icons[2].def;
          menuList[2].selectedIconPath = icons[2].act;
        }
        if (menuList[3].iconType === 1) {
          menuList[3].iconPath = icons[3].def;
          menuList[3].selectedIconPath = icons[3].act;
        }
        if (menuList[4].iconType === 1) {
          menuList[4].iconPath = icons[4].def;
          menuList[4].selectedIconPath = icons[4].act;
        }
      }
      return menuList;
    },
    /**
     * @description 获取并处理页面控件
     * @param navBarPlugin 控件数据
     */
    getPlugins(context, navBarPlugin) {
      if (!navBarPlugin || !navBarPlugin.length) { return }
      context.commit('setHomeTab', navBarPlugin[0])
      navBarPlugin.forEach((item: { type: number; }, index: number) => {
        if (item.type === 5) {
          navBarPlugin[index].name = "home";
        }
      });
      const tabBar = {
        ...context.state.tabBar,
        list: navBarPlugin,
      }
      context.commit('setTabBar', tabBar)
      const navbarHome = navBarPlugin.filter((item: { isHome: boolean; }) => {
        return item.isHome;
      });
      if (navbarHome.length > 0) {
        if (navbarHome[0].type === 5) {
          context.commit('setCurrentPageId', navbarHome[0].id)
          context.commit('setCurrentTab', "home")
        } else {
          context.commit('setCurrentPageId', "")
          context.commit('setCurrentTab', navbarHome[0].name)
        }
      }
    },
    /**
     * @description 设置大图模式
     * @param navBarform 
     */
    settingBigPic(context, navBarform) {
      const listLen = context.state.tabBar.list.length;
      const centerNum = Math.floor(listLen / 2);

      const centerTabbarItem = isPrimeNum(listLen) ? Object.assign({}, context.state.tabBar.list[centerNum], {
        centerNum,
      }) : null;
      const tabBar = {
        ...context.state.tabBar,
      }
      if (navBarform && navBarform.codeStyle === 2) {
        tabBar.mode = "center";
      } else {
        tabBar.mode = "default";
      }
      context.commit('setCenterTabbarItem', centerTabbarItem)
      context.commit('setTabBar', tabBar)
    },

    /**
     * @description 获取积分规则
     */
    async getRule(context) {
      const res = await getIntegralRule({});
      if (res && !isEqual(res, storage.get("getRuleData"))) {
        storage.set("getRuleData", res, 3 * 24 * 60 * 60 * 1000);
      }
      const storageData = storage.get("getRuleData");
      context.commit('setIntegral', storageData ? storageData[1].open : false)
    },

    /**
     * @description 返回首页公共方法
     */
    backHome(context) {
      const { linkUrl, name, type, id } = context.state.homeTab;
      console.log('homeTab',context.state.homeTab)
      if (linkUrl === "/pages/index/index" || linkUrl === "pages/index/index") {
        context.commit('setIndexTitle', context.state.shopSetting.curShopInfoDto.shopName)
        context.commit('setCurrentTab', name)
        context.commit('setCurrentPageId', "")
        context.commit('setCustomPageId', "")
        context.commit('setHasInCustom', true)
        context.commit('setIsReSet', false)
        if (type === 5) {
          context.commit('setCurrentPageId', id)
          const newPages = context.state.pageList.filter((item: { isDef: string; }) => {
            return item.isDef === "1";
          });
          context.commit('setNewCurrentPageId', newPages[0].id)
        }
        uni.reLaunch({
          url: `/pages/index/index`,
        });
      }
    },

  }
}

export default module;
